package com.example.peibei.ui.activity;

import android.Manifest;
import android.app.AlertDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.dingtao.common.core.DataCall;
import com.dingtao.common.core.WDActivity;
import com.dingtao.common.core.exception.ApiException;
import com.dingtao.common.util.SPUtils;
import com.dingtao.common.util.UIUtils;
import com.example.peibei.R;
import com.example.peibei.base.SpConstant;
import com.example.peibei.bean.CityBean;
import com.example.peibei.service.presenter.ChcekTextPresenter;
import com.example.peibei.service.presenter.SendOrderPresenter;
import com.example.peibei.service.presenter.UploadImagePresenter;
import com.example.peibei.ui.weight.GlideEngine;
import com.example.peibei.ui.weight.MoneyKeyboardDialog;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.yxp.permission.util.lib.PermissionUtil;
import com.yxp.permission.util.lib.callback.PermissionResultCallBack;

import org.greenrobot.eventbus.EventBus;

import java.io.ByteArrayOutputStream;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

//import com.wildma.pictureselector.PictureSelector;

public class ChooseOrderContentActivity extends WDActivity {
    @BindView(R.id.et_order)
    EditText et_order;
    @BindView(R.id.iv_img_one)
    ImageView iv_img_one;
    @BindView(R.id.rl_add_one)
    LinearLayout rl_add_one;
    @BindView(R.id.iv_img_two)
    ImageView iv_img_two;
    @BindView(R.id.rl_add_two)
    LinearLayout rl_add_two;
    @BindView(R.id.iv_img_three)
    ImageView iv_img_three;
    @BindView(R.id.rl_add_three)
    LinearLayout rl_add_three;
    @BindView(R.id.rl_edit_money)
    RelativeLayout rl_edit_money;
    @BindView(R.id.rl_edit_money_right)
    RelativeLayout rl_edit_money_right;
    @BindView(R.id.et_money)
    EditText et_money;
    @BindView(R.id.tv_city_name)
    TextView tv_city_name;
    @BindView(R.id.tv_money)
    TextView tv_money;
    @BindView(R.id.rb_yikoujia)
    RadioButton rb_yikoujia;
    @BindView(R.id.rd_xiaoshi)
    RadioButton rd_xiaoshi;

    private int categoryId;
    private String timeLimit;
    String imagePathOne = "";
    String imagePathTwo = "";
    String imagePathThree = "";
    private UploadImagePresenter uploadImagePresenter;
    private SendOrderPresenter sendOrderPresenter;
    private SPUtils spUtils;
    private String token;
    private String cityName;
    private String cityCode;
    private ChcekTextPresenter chcekTextPresenter;
    private String content;
    public AMapLocationClient mLocationClient = null;
    private int unit = -1;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_choose_order_content;
    }

    @Override
    protected void initView() {
        Intent intent = getIntent();
        Bundle bundle = intent.getExtras();
        categoryId = bundle.getInt("categoryId");
        timeLimit = bundle.getString("timeLimit");
        spUtils = new SPUtils(this, SpConstant.USER_TOKEN);
        token = spUtils.getString(SpConstant.USER_TOKEN);
        cityName = spUtils.getString(SpConstant.CITY_NAME);
        cityCode = spUtils.getString(SpConstant.CITY_CODE);
        if (TextUtils.isEmpty(cityName)) {
            tv_city_name.setText("请选择");
        } else {
            tv_city_name.setText(cityName);
        }
        uploadImagePresenter = new UploadImagePresenter(new UploadCall());
        sendOrderPresenter = new SendOrderPresenter(new SendOrderCall());
        chcekTextPresenter = new ChcekTextPresenter(new CheckTextCall());
        rl_add_one.setOnClickListener(v -> showChooseImageDialog());
        rl_add_two.setOnClickListener(v -> showChooseImageDialog());
        rl_add_three.setOnClickListener(v -> showChooseImageDialog());
        rl_edit_money.setOnClickListener(v -> {
            String money = et_money.getText().toString().trim();
            int i;
            if (!money.equals("")) {
                int integer = Integer.parseInt(money);
                if (integer > 1) {
                    i = integer - 1;
                    et_money.setText(i + "");
                }
            }
        });
        rl_edit_money_right.setOnClickListener(v -> {
            String money = et_money.getText().toString().trim();
            int i;
            if (!money.equals("")) {
                int integer = Integer.parseInt(money);
                i = integer + 1;
                et_money.setText(i + "");
            }
        });
        rb_yikoujia.setChecked(true);
        CompoundButton.OnCheckedChangeListener onCheckedChangeListener = new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (b) {
                    compoundButton.setTextColor(Color.WHITE);
                } else {
                    compoundButton.setTextColor(Color.BLACK);
                }
                if (compoundButton == rb_yikoujia){
                    if (b){
                        unit = -1;
                    }
                }else if (compoundButton == rd_xiaoshi){
                    if (b){
                        unit = 0;
                    }
                }
            }
        };
        rb_yikoujia.setOnCheckedChangeListener(onCheckedChangeListener);
        rd_xiaoshi.setOnCheckedChangeListener(onCheckedChangeListener);
    }

    @OnClick(R.id.iv_back)
    public void back() {
        finish();
    }

    @OnClick(R.id.tv_city_name)
    public void local() {
        getLocalPermission();
    }

    @OnClick(R.id.layout_set_money)
    public void setMoney(){

        MoneyKeyboardDialog dialog = new MoneyKeyboardDialog(this);
        dialog.create(new MoneyKeyboardDialog.OnMoneyListener() {
            @Override
            public void onMoney(String money) {
                tv_money.setText(money);
            }
        });
    }

    @OnClick(R.id.btn_submit)
    public void submit() {
        content = et_order.getText().toString().trim();
        if (content.equals("")) {
            UIUtils.showToastSafe("内容不能为空");
            return;
        }
        if (TextUtils.isEmpty(cityCode)||TextUtils.isEmpty(cityName)){
            UIUtils.showToastSafe("请选择当前位置");
            return;
        }
        chcekTextPresenter.reqeust("Bearer " + token, content);
    }

    private void showChooseImageDialog() {
//        PictureSelector
//                .create(ChooseOrderContentActivity.this, PictureSelector.SELECT_REQUEST_CODE)
//                .selectPicture(true);
        getPermission();
    }

    private static String[] PERMISSIONSLOCAL = {
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_LOCATION_EXTRA_COMMANDS,
            Manifest.permission.ACCESS_FINE_LOCATION
    };

    private void getLocalPermission() {
        PermissionUtil.getInstance().request(this, PERMISSIONSLOCAL,
                new PermissionResultCallBack() {
                    @Override
                    public void onPermissionGranted() {
                        // 当所有权限的申请被用户同意之后,该方法会被调用

                        //隐私政策合规
                        AMapLocationClient.updatePrivacyShow(getApplicationContext(), true, true);
                        AMapLocationClient.updatePrivacyAgree(getApplicationContext(), true);
                        //初始化定位
                        try {
                            mLocationClient = new AMapLocationClient(getApplicationContext());
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                        //声明定位回调监听器
                        AMapLocationListener mLocationListener = new AMapLocationListener() {
                            @Override
                            public void onLocationChanged(AMapLocation aMapLocation) {
                                Log.i("answer", aMapLocation.getCity());//城市信息
                                Log.i("answer", aMapLocation.getCityCode());//城市信息
                                cityName = aMapLocation.getCity();
                                cityCode = aMapLocation.getCityCode();
                                tv_city_name.setText(cityName);
                                spUtils.putString(SpConstant.CITY_NAME, aMapLocation.getCity());
                                spUtils.putString(SpConstant.CITY_CODE, aMapLocation.getCityCode());
                                CityBean cityBean = new CityBean(aMapLocation.getCity(), aMapLocation.getCityCode());
                                EventBus.getDefault().post(cityBean);
                            }
                        };
                        //设置定位回调监听
                        mLocationClient.setLocationListener(mLocationListener);
                        AMapLocationClientOption option = new AMapLocationClientOption();
                        option.setOnceLocation(true);

                        //给定位客户端对象设置定位参数
                        mLocationClient.setLocationOption(option);
                        //启动定位
                        mLocationClient.startLocation();
                    }

                    @Override
                    public void onPermissionGranted(String... strings) {
                        // 当所有权限的申请被用户同意之后,该方法会被调用
                        //get_NovelUrl(id);
                    }

                    @Override
                    public void onPermissionDenied(String... permissions) {
                        spUtils.putString(SpConstant.CITY_NAME, "");
                        spUtils.putString(SpConstant.CITY_CODE, "");
//                        UIUtils.showToastSafe("部分权限被禁止需要手动开启");
                        // 当权限申请中的某一个或多个权限,被用户曾经否定了,并确认了不再提醒时,也就是权限的申请窗口不能再弹出时,该方法将会被调用
//                        getPermission();
                    }

                    @Override
                    public void onRationalShow(String... permissions) {
                        spUtils.putString(SpConstant.CITY_NAME, "");
                        spUtils.putString(SpConstant.CITY_CODE, "");
//                        UIUtils.showToastSafe("部分权限被禁止需要手动开启");
                        // 当权限申请中的某一个或多个权限,被用户否定了,但没有确认不再提醒时,也就是权限窗口申请时,但被否定了之后,该方法将会被调用.
//                        getPermission();
                    }

                });
    }

    private static String[] PERMISSIONS = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.CAMERA
    };

    private void getPermission() {
        PermissionUtil.getInstance().request(this, PERMISSIONS,
                new PermissionResultCallBack() {
                    @Override
                    public void onPermissionGranted() {
                        showAlbum();
                    }

                    @Override
                    public void onPermissionGranted(String... strings) {
                        // 当所有权限的申请被用户同意之后,该方法会被调用
                        //get_NovelUrl(id);
                    }

                    @Override
                    public void onPermissionDenied(String... permissions) {

                        UIUtils.showToastSafe("部分权限被禁止需要手动开启");

                        // 当权限申请中的某一个或多个权限,被用户曾经否定了,并确认了不再提醒时,也就是权限的申请窗口不能再弹出时,该方法将会被调用
                        getPermission();
                    }

                    @Override
                    public void onRationalShow(String... permissions) {
                        UIUtils.showToastSafe("部分权限被禁止需要手动开启");
                        // 当权限申请中的某一个或多个权限,被用户否定了,但没有确认不再提醒时,也就是权限窗口申请时,但被否定了之后,该方法将会被调用.
                        getPermission();
                    }

                });
    }

    private void showAlbum() {
        PictureSelector.create(ChooseOrderContentActivity.this)
                .openGallery(PictureMimeType.ofImage())
                .loadImageEngine(GlideEngine.createGlideEngine())
                .maxSelectNum(1)
                .minSelectNum(1)
                .compress(true)
                .selectionMode(PictureConfig.SINGLE)
                .forResult(PictureConfig.CHOOSE_REQUEST);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        /*结果回调*/
        if (requestCode == PictureConfig.CHOOSE_REQUEST) {
            if (data != null) {
                List<LocalMedia> localMedia = PictureSelector.obtainMultipleResult(data);
                uploadImage(localMedia.get(0).getCompressPath());
            }
        }
    }

    private void uploadImage(String imagePath) {
        if (imagePathOne.equals("")) {
            rl_add_one.setVisibility(View.GONE);
            rl_add_two.setVisibility(View.VISIBLE);
//            iv_img_one.setImageBitmap(BitmapFactory.decodeFile(imagePath));
//            Bitmap bitmap=BitmapFactory.decodeFile(imagePath);
            iv_img_one.setImageBitmap(BitmapFactory.decodeFile(imagePath));
        } else {
            if (imagePathTwo.equals("")) {
                rl_add_two.setVisibility(View.GONE);
                rl_add_three.setVisibility(View.VISIBLE);
                iv_img_two.setImageBitmap(BitmapFactory.decodeFile(imagePath));
            } else {
                rl_add_three.setVisibility(View.GONE);
                iv_img_three.setImageBitmap(BitmapFactory.decodeFile(imagePath));
            }
        }
        uploadImagePresenter.reqeust(imagePath, "Bearer " + token);
    }

    private Bitmap compressQuality(Bitmap bitmap) {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 30, bos);
        byte[] bytes = bos.toByteArray();
        Log.e("bitmapsize", String.valueOf(bytes.length));
        return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
    }

    class UploadCall implements DataCall<String> {

        @Override
        public void success(String data, Object... args) {
            Log.i("answer", "图片上传成功：" + data);
            if (imagePathOne.equals("")) {
                imagePathOne = data;
            } else {
                if (imagePathTwo.equals("")) {
                    imagePathTwo = data;
                } else {
                    imagePathThree = data;
                }
            }
        }

        @Override
        public void fail(ApiException e, Object... args) {
            UIUtils.showToastSafe("您的输入含有不合法的内容或图片，请遵守用户协议相关内容");
        }
    }

    class SendOrderCall implements DataCall<String> {

        @Override
        public void success(String data, Object... args) {
            UIUtils.showToastSafe("发布成功");
            intent(MainActivity.class);
            finish();
        }

        @Override
        public void fail(ApiException e, Object... args) {
            UIUtils.showToastSafe(e.getDisplayMessage());
        }

    }

    class CheckTextCall implements DataCall<String> {

        @Override
        public void success(String data, Object... args) {
            String filePath = imagePathOne;
            if (!imagePathTwo.equals("")) {
                filePath = imagePathOne + "," + imagePathTwo;
            }
            if (!imagePathThree.equals("")) {
                filePath = imagePathOne + "," + imagePathTwo + "," + imagePathThree;
            }
            if (TextUtils.isEmpty(filePath)) {
                UIUtils.showToastSafe("图片不能为空");
                return;
            }
            String money = tv_money.getText().toString().trim();
            if (TextUtils.isEmpty(money)) {
                UIUtils.showToastSafe("金额不能为空");
                return;
            }
            sendOrderPresenter.reqeust("Bearer " + token, categoryId, cityCode, cityName, "", filePath, 0.0, 0.0, content, Double.parseDouble(money), timeLimit, unit);
        }

        @Override
        public void fail(ApiException e, Object... args) {
            UIUtils.showToastSafe(e.getDisplayMessage());
        }

    }

    @Override
    protected void destoryData() {

    }
}
